/********************************************************************************************************************************* 
 * NaviCore Corporate MIT License 0.1
 * Copyright (c) 2019 GIS Core R&D Department, NavInfo Corp.
 *
 * Permission is hereby granted, free of charge, to any entity within the corporation(Entity) obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, including without 
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit Entities to whom the Software is furnished to do so, subject to the following conditions:
 *
 * 1. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. and
 * 2. The above copyright notice, this permission notice and the acknowledgments below shall be displayed in UI or web pages 
 *    if the Software is redistributed in binary form or as web service.
 *
 *    Acknowledgments: "This work uses NaviZeroAndroid provided by GIS Core R&D Department, NavInfo Corp."
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * You may also get a copy of the license at http://navicore.cn/license/NC_MIT_0.1
 **********************************************************************************************************************************/
package com.cennavi.minenavidemo.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.media.AudioManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.minedata.minenavi.SDKInitializer;
import com.minedata.minenavi.map.MineMap;
import com.minedata.minenavi.mapdal.DistanceStringInfo;
import com.minedata.minenavi.mapdal.MineNaviUtil;
import com.minedata.minenavi.mapdal.NativeEnv;

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class Utils {

	private Context mContext;
	private AudioManager mAudioManager;
	private PackageManager mPackageManager;
	private float mDpiFactor = 2.0f;
	private boolean mIsInited = false;
	private Timer mTimer;
	private Context mApplicationContext;
	private CountDownTimer mCountDownTimer;

	private static class SingletonHolder {
		public static final Utils instance = new Utils();
	}

	public static Utils getInstance() {
		return SingletonHolder.instance;
	}

	public void init(Context context) {
		if (mIsInited) {
			return;
		}
		mContext = context;
		mApplicationContext = context.getApplicationContext();
		mTimer = new Timer();
		mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
		mPackageManager = mContext.getPackageManager();
		mDpiFactor = context.getResources().getDisplayMetrics().density;
		mIsInited = true;
	}

	/**
	 * 获取当前音量值
	 */
	public int getCurrentVolume() {
		return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
	}

	/**
	 * 获取音量最大值
	 */
	public int getMaxVolume() {
		return mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
	}

	/**
	 * 设置当前的音量
	 */
	public void setVolume(int volumeValue) {
		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumeValue, AudioManager.FLAG_PLAY_SOUND);//设置值为Val
	}

	/**
	 * APP是否处于前台
	 */
	public boolean isAppOnForeground() {
		ActivityManager activityManager = (ActivityManager) mContext.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
		String packageName = mContext.getApplicationContext().getPackageName();
		List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses == null)
			return false;

		for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
			if (appProcess.processName.equals(packageName)
					&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 判断设备是否正在充电
	 */
	public boolean isCharging() {
		IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		Intent batteryStatus = mContext.registerReceiver(null, ifilter);
		int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
		boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
				status == BatteryManager.BATTERY_STATUS_FULL;
		return isCharging;
	}

	/**
	 * 获取屏幕的高,如果横屏的话,返回的高就是屏幕的宽,如果是竖屏的话,返回的高就是屏幕的高，获取的高是从状态栏到导航栏整体的高
	 *
	 * @param activity 当前的activity
	 * @return 屏幕的高
	 */
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
	public int getWindowHeight(Activity activity) {
		Point realSize = new Point();
		activity.getWindowManager().getDefaultDisplay().getRealSize(realSize);
		return realSize.y;
	}

	/**
	 * 获取屏幕的高,如果横屏的话,返回的高就是屏幕的宽,如果是竖屏的话,返回的高就是屏幕的高，获取的高是从状态栏到导航栏整体的高
	 *
	 * @param activity 当前的activity
	 * @return 屏幕的高
	 */
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
	public int getWindowWidth(Activity activity) {
		Point realSize = new Point();
		activity.getWindowManager().getDefaultDisplay().getRealSize(realSize);
		return realSize.x;
	}

	/**
	 * 平移动画
	 */
	private TranslateAnimation mTranslateAnimation;

	public void translateAnimation(View view, float fromX, float toX, float fromY, float toY, long duration, Animation.AnimationListener animationListener,
                                   boolean isFillAfter) {
		mTranslateAnimation = new TranslateAnimation(
				Animation.RELATIVE_TO_SELF, fromX, Animation.RELATIVE_TO_SELF, toX,
				Animation.RELATIVE_TO_SELF, fromY, Animation.RELATIVE_TO_SELF, toY);
		mTranslateAnimation.setDuration(duration);
		mTranslateAnimation.setFillAfter(isFillAfter);
		if (animationListener != null) {
			mTranslateAnimation.setAnimationListener(animationListener);
		}
		view.startAnimation(mTranslateAnimation);
	}

	/**
	 * 混合动画动画
	 */

	public void translateAnimationWithAbsolute(View view, float fromAlpha, float toAlpha, long alaphDuration, long startTime, float fromX, float toX, float fromY, float toY,
                                               long translateDuration, long animationSetDuration, Animation.AnimationListener animationListener,
                                               boolean isFillAfter) {
		//途径点1——————————添加文字移动平移动画    333
		AnimationSet animationSet = new AnimationSet(true);
		AlphaAnimation animationa = new AlphaAnimation(fromAlpha, toAlpha);
		animationa.setDuration(alaphDuration);
		animationa.setStartTime(startTime);
		animationSet.addAnimation(animationa);
		TranslateAnimation translateAnimation = new TranslateAnimation(Animation.ABSOLUTE, fromX, Animation.ABSOLUTE, toX, Animation.ABSOLUTE,
				fromY, Animation.ABSOLUTE, toY);
		translateAnimation.setDuration(translateDuration);
		animationSet.addAnimation(translateAnimation);
		animationSet.setDuration(animationSetDuration);
		animationSet.setAnimationListener(animationListener);
		animationSet.setFillAfter(isFillAfter);
		view.startAnimation(animationSet);
	}

	public boolean isTranslateAnimationHasEnded() {
		if (mTranslateAnimation == null) {
			return true;
		}
		return mTranslateAnimation.hasEnded();
	}

	/**
	 * 地图是否是2d模式
	 */
	public final boolean isMap2dStyle(MineMap mineMap) {
		return mineMap.getElevation() == 90;
	}

	/**
	 * 地图是否是3d模式
	 */
	public final boolean isMap3dStyle(MineMap mineMap) {
		return mineMap.getElevation() != 90;
	}

	/**
	 * 延时操作
	 *
	 * @param runnable
	 * @param delayed
	 */
	private Handler delayedViewOperateHandler = new Handler();

	public void doDelayedViewOperate(Runnable runnable, long delayed) {
		delayedViewOperateHandler.postDelayed(runnable, delayed);
	}

	public Handler getDelayedViewOperateHandler() {
		return delayedViewOperateHandler;
	}

	public void cleanup() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
	}

	/**
	 * 秒转换成分钟，向上取整
	 *
	 * @param secondTime 秒
	 * @return 取整后的分钟
	 */
	public final int second2Minute(int secondTime) {
		return (secondTime + 59) / 60;
	}

	/**
	 * 将以秒为单位的时间格式化
	 *
	 * @param secondTime 秒
	 * @return 得到格式化的时间
	 */
	public String formatTime(int secondTime) {
		String sTotalTime;
		int minutes = second2Minute(secondTime);
		if (minutes < 60) {
			sTotalTime = minutes + "分钟";
		} else {
			int remainMin = minutes % 60;
			sTotalTime = minutes / 60 + "小时" + (remainMin == 0 ? "" : remainMin + "分");
		}
		return sTotalTime;
	}

	/**
	 * 格式化到千米，如果距离不小于100km或整千米，保留整数；否则保留小数点后一位，比如 110000 -> 110，8000 -> 8, 8001 -> 8, 800 -> 0.8, 99 -> 0
	 *
	 * @param distance 距离，单位：米
	 * @return 格式化后以千米表示的结果，不包含单位
	 */
	public String formatDistanceToKm(int distance) {
		String distanceValue;
		if (distance >= 100000 || distance % 1000 == 0) {
			distanceValue = String.valueOf(distance / 1000);
		} else {
			distanceValue = String.format(Locale.getDefault(), "%.1f", (distance / 100) / 10.0);
		}
		return distanceValue;
	}

	public DistanceBean formatDistance(int distance, boolean isEnglishDistanceUnit) {
		DistanceStringInfo distanceStringInfo = MineNaviUtil.distance2String(distance, isEnglishDistanceUnit ? MineNaviUtil.DistanceUnit.english : MineNaviUtil.DistanceUnit.normal, false);
		String distanceValue = "";
		String distanceUnit = "";
		switch (distanceStringInfo.unit) {
			case MineNaviUtil.GisUnit.m:
				distanceUnit = isEnglishDistanceUnit ? "m" : "米";
				break;
			case MineNaviUtil.GisUnit.km:
				distanceUnit = isEnglishDistanceUnit ? "km" : "公里";
				break;
			case MineNaviUtil.GisUnit.mi:
				distanceUnit = isEnglishDistanceUnit ? "mile" : "英里";
				break;
			case MineNaviUtil.GisUnit.ft:
				distanceUnit = isEnglishDistanceUnit ? "ft" : "英尺";
				break;
		}
		distanceValue = distanceStringInfo.distanceString.split(distanceUnit)[0];
		return new DistanceBean(distanceValue, distanceUnit);
	}

	public TimeBean calcTimeBean(int time) {
		int totalMinute = (time + 59) / 60;
		int timeHour = totalMinute / 60;
		int timeMinute = totalMinute % 60;
		return new TimeBean(timeHour, timeMinute);
	}

	/**
	 * 弹出/隐藏键盘
	 */
	public void enableInputMethod(boolean enable, EditText editText) {
		InputMethodManager inputManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (enable) {
			//弹出键盘
			inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		} else {
			//隐藏键盘
			inputManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
		}
	}

	/**
	 * 弹出/隐藏键盘 : 防止焦点丢失
	 */
	public void enableInputMethodWithFocus(boolean enable, EditText editText) {
		InputMethodManager inputManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		editText.setFocusable(enable);
		editText.setFocusableInTouchMode(enable);
		editText.requestFocus();
		if (enable) {
			//弹出键盘
			editText.requestFocus();
			inputManager.showSoftInput(editText, 0);
		} else {
			//隐藏键盘
			inputManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
		}
	}

	/**
	 * 光标移到文字后
	 */
	public void setSelectionEnd(EditText editText) {
		if (editText != null) {
			String b = editText.getText().toString();
			editText.setSelection(b.length());
		}
	}

	/**
	 * 无焦点情况下隐藏键盘
	 */
	public void hideKeyboard(Context context) {
		Activity activity = (Activity) context;
		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		View v = activity.getWindow().peekDecorView();
		if (null != v) {
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
		}
	}


	public String getStrDistance(Point point1, Point point2) {
		int distance = MineNaviUtil.distance(point1, point2);
		return MineNaviUtil.distance2String(distance, MineNaviUtil.DistanceUnit.normal, false).distanceString;
	}

	public int dp2Px(float dp) {
		return (int) (dp * mDpiFactor + 0.5f);
	}

	public int px2Dp(int px) {
		return (int) (px / mDpiFactor + 0.5f);
	}

	/**
	 * 判断系统当前是24小时制还是 12小时制
	 */
	public boolean is24Hour() {
		return android.text.format.DateFormat.is24HourFormat(mContext);
	}

	/**
	 * 将流量大小(B)格式化为显示文本，规则如下：<br>
	 * 1. 小于1K时，显示xxB，例如2B<br>
	 * 2. 小于1M时，显示xxKB，例如250KB<br>
	 * 3. 小于1G时，显示xxMB，例如250MB<br>
	 * 4. 不小于1G时，显示xx.xGB，例如1.0GB, 10.5GB
	 *
	 * @param size 流量大小，单位：字节
	 */
	public String formatTrafficDataSize(long size) {
		if (size < 1024) {
			return size + "B";
		} else if (size < 1024 * 1024) {
			return size / 1024 + "KB";
		} else if (size < 10 * 1024 * 1024) {
			return String.format("%.1fM", size / (1024.0 * 1024));
		} else if (size < 1024L * 1024 * 1024) {
			return size / (1024 * 1024) + "MB";
		} else {
			return String.format("%.1fGB", size / (1024.0 * 1024 * 1024));
		}
	}

	/**
	 * 获取版本号名字
	 */
	public String getVerName() {
		String verName = "";
		try {
			verName = mPackageManager.getPackageInfo(mApplicationContext.getPackageName(), 0).versionName;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return verName;
	}

	/**
	 * 获取版本号
	 */
	public int getVersionCode() {
		int versionCode = 0;
		try {
			versionCode = mPackageManager.getPackageInfo(mApplicationContext.getPackageName(), 0).versionCode;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	/**
	 * 获取app名字
	 */
	public String getAppName() {
		String appName = "";
		try {
			PackageInfo packageInfo = mPackageManager.getPackageInfo(mApplicationContext.getPackageName(), 0);
			appName = packageInfo.applicationInfo.loadLabel(mPackageManager).toString();
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return appName;
	}

	/**
	 * 全角转半角
	 *
	 * @return 半角字符串
	 */
	public String toDBC(String input) {
		char c[] = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == '\u3000') {
				c[i] = ' ';
			} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
				c[i] = (char) (c[i] - 65248);
			}
		}
		return new String(c);
	}

	/**
	 * 系统Toast
	 */
	public void showToast(Context context, String msg) {
		Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
		toast.setText(msg);
		toast.show();
	}

	public void scheduleTimerTask(TimerTask timerTask, long time) {
		if (mTimer != null && timerTask != null) {
			mTimer.schedule(timerTask, time);
		}
	}

	/**
	 * 软件运行环境是否是手机
	 *
	 * @return
	 */
	public boolean isMobilePhone() {
		try {
			if (ScreenUtil.getInstance().isScreenLandscape() && getTotalRam(mContext) <= 2.0f
					&& getSdcardAvailableSize(SDKInitializer.getAppPath()) < (25L * 1024 * 1024 * 1024)) {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * 根据包名获取当前数据存储的路径后缀
	 */
	public String getCurrentStoragePathSuffix() {
		String suffix = "";
		if (isTestVersion()) {
			suffix = "/mapbar/NaviZero";
		} else if (isReleaseVersion()) {
			suffix = "/mapbar/NaviZeroRelease";
		}
		return suffix;
	}

	public boolean isTestVersion() {
		String packageName = mContext.getPackageName();
		return TextUtils.equals("com.mapbar.navigation.zero", packageName);
	}

	public boolean isReleaseVersion() {
		String packageName = mContext.getPackageName();
		return TextUtils.equals("com.mapbar.navigation.zero.release", packageName);
	}

	public String getLoginAppName() {
		return isTestVersion() ? "naviZeroBeta" : "naviZeroRelease";
	}

	/**
	 * 获取SD卡大小
	 *
	 * @param sdcardPath
	 * @return
	 */
	public long getSdcardAvailableSize(String sdcardPath) {
		long size = 0;
		StatFs statFs = new StatFs(sdcardPath);
		int blockSize = statFs.getBlockSize();
		int totalBlocks = statFs.getBlockCount();
		size = (long) totalBlocks * blockSize;
		return size;
	}

	public float getTotalRam(Context context) {
		String path = "/proc/meminfo";
		String firstLine = null;
		float totalRam = 0;
		try {
			FileReader fileReader = new FileReader(path);
			BufferedReader br = new BufferedReader(fileReader, 8192);
			firstLine = br.readLine().split("\\s+")[1];
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (firstLine != null) {
			totalRam = Float.valueOf(firstLine) / (1024 * 1024);
		}
		return totalRam;
	}

	public Bitmap createCircleBitmap(Bitmap resource) {
		//获取图片的宽度
		int width = resource.getWidth();
		Paint paint = new Paint();
		//设置抗锯齿
		paint.setAntiAlias(true);

		//创建一个与原bitmap一样宽度的正方形bitmap
		Bitmap circleBitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
		//以该bitmap为低创建一块画布
		Canvas canvas = new Canvas(circleBitmap);
		//以（width/2, width/2）为圆心，width/2为半径画一个圆
		canvas.drawCircle(width / 2, width / 2, width / 2, paint);

		//设置画笔为取交集模式
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		//裁剪图片
		canvas.drawBitmap(resource, 0, 0, paint);

		return circleBitmap;
	}

	private SimpleDateFormat mSimpleDateFormat;

	/**
	 * local时间转换成UTC时间
	 *
	 * @param date 时间格式 例： 2019-5-21 14:12:38
	 * @return 返回格式化好的时间 例： 2019-5-21 22:12:38
	 */
	public String formatLocalDate(String date) {
		if (mSimpleDateFormat == null) {
			mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
		Date localDate = null;
		try {
			localDate = mSimpleDateFormat.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		long localTimeInMillis = localDate.getTime() + 60 * 60 * 8 * 1000;
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(localTimeInMillis);
		return mSimpleDateFormat.format(calendar.getTime());
	}

	/**
	 * /**
	 * 使用SHA1算法对字符串进行加密
	 *
	 * @param str 要签名的字符串
	 * @return SHA1 签名后的内容
	 */
	public static String sha1Digest(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f'};
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes("UTF-8"));
			byte[] md = mdTemp.digest();
			int j = md.length;
			char buf[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
				buf[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(buf);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 随机字符串
	 *
	 * @return 随机字符串
	 */
	public static String randomString() {
		String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 10; i++) {
			int number = random.nextInt(str.length());
			char charAt = str.charAt(number);
			sb.append(charAt);
		}
		return sb.toString();
	}

	/**
	 * 开启横竖屏模式
	 *
	 * @param activity 需要开启横竖屏的activity
	 * @param isOpen   是否打开
	 */
	public void enableHorizontalAndVerticalScreenMode(Activity activity, boolean isOpen) {
		activity.setRequestedOrientation(isOpen ? ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}


	/**
	 * 开启横竖屏模式
	 *
	 * @param isOpen 是否打开
	 */
	public void enableHorizontalAndVerticalScreenMode(boolean isOpen) {
		enableHorizontalAndVerticalScreenMode((Activity) mContext, isOpen);
	}

	/**
	 * 是否有网络连接
	 *
	 * @return
	 */
	public boolean isHaveNetwork() {
		int netWorkState = NativeEnv.getNetworkStatus(mContext);

		if (netWorkState == NativeEnv.NetworkStatus.unavailable) {
			return false;
		}

		return true;
	}

	public boolean isNumber(String str) {
		for (int i = str.length(); --i >= 0; ) {
			int chr = str.charAt(i);
			if (chr < 48 || chr > 57)
				return false;
		}
		return true;
	}

	/***
	 * MD5加密
	 */
	public static String string2MD5(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}

		byte[] md5Bytes = md5.digest(inStr.getBytes());
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString().toUpperCase();
	}

	public static String base64(String str) {
		return Base64.encodeToString(str.getBytes(), Base64.DEFAULT);
	}

	public static String location2String(Point pt) {
		return String.format("%.5f,%.5f", pt.x / 100000.0, pt.y / 100000.0);
	}

	public static Point string2Location(String str) {
		try {
			String[] parts = str.split(",");
			return new Point((int) (Float.valueOf(parts[0]) * 100000), (int) (Float.valueOf(parts[1]) * 100000));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
